package org.shj.spark.streaming;

import java.util.Arrays;
import java.util.Iterator;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import scala.Tuple2;

/**
 * apt-get install nc
 * nc -lk 8888
 * 
 * 一个Spark Streaming应用程序可以创建若干个SparkStreamingContext，使用下一个SparkStreamingContext
 * 之前，需要把前一个SparkStreamingContext对象关掉。 SparkStreaming其实就是运行在Spark Core上的一个应用程序
 * 而已，
 * 
 * @author Administrator
 *
 */
public class StreamingWordCount {

	public static void main(String[] args) throws Exception {
		/**
		 * 集群模式下，对于处理Spark Streaming的应用程序而言，每个Executor分配5个core为最佳值 
		 */
		SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("StreamingWordCount");
		
		//第二个参数是指：每收集多长时间的数据就划分一个RDD去执行
		//如果在时间间隔内没有数据的话，会启动空的Job，这样是会造成调度资源的浪费。实际应用中，在提交Job之前应该判断一下。
		JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(5));
		
		JavaReceiverInputDStream<String> lines = jsc.socketTextStream("ubuntu1", 8888);
		
		JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
			private static final long serialVersionUID = 1L;

			public Iterator<String> call(String line) throws Exception {
				return Arrays.asList(line.split(" ")).iterator();
			}
		});

		JavaPairDStream<String, Integer> pair = words.mapToPair(new PairFunction<String, String, Integer>() {
			private static final long serialVersionUID = 2823007325722993181L;

			@Override
			public Tuple2<String, Integer> call(String word) throws Exception {
				return new Tuple2<String, Integer>(word, 1);
			}
		});
		
		JavaPairDStream<String, Integer> wordCount = pair.reduceByKey(new Function2<Integer, Integer, Integer>() {
			private static final long serialVersionUID = 8560445270191804880L;

			@Override
			public Integer call(Integer v1, Integer v2) throws Exception {
				return v1 + v2;
			}
		});
		
		wordCount.print();
		
		jsc.start();
		jsc.awaitTermination();
		jsc.close();
	}

}
